import React from 'react';
import ReactDOM from 'react-dom';

class Sum extends React.Component {
  a: HTMLInputElement | null = null;
  b: HTMLInputElement | null = null;
  c: HTMLInputElement | null = null;
  add = () => {
    let a = this.a!.value; //省去了this.refs.a的refs
    let b = this.b!.value;
    (this.c as HTMLInputElement).value = (parseInt(a) + parseInt(b)) + '';
  };

  componentDidMount() {
    console.log('componentDidMount---');
    console.log('this.a:',this.a); //this.a: <input>
  }

  render() {
    return (
      <>
        {/**
         该回调函数会在虚拟dom转换成真实dom以后 将真实dom作为参数传进来并调用
         这种形式 因为可以在回调里干任何事 So 不一定能在组件实例上通过一个属性拿到该ref对应的dom(如果不手动进行赋值的话)
         */}
        <input ref={(input: HTMLInputElement) => {console.log('会在componentDidMount之前执行,但这时能拿到dom对象');this.a = input}}/>+
        <input ref={(input: HTMLInputElement) => this.b = input}/>
        <button onClick={this.add}>=</button>
        <input ref={(input: HTMLInputElement) => this.c = input}/>
      </>
    );
  }
}

/*
Refs are guaranteed to be up-to-date before componentDidMount or componentDidUpdate fires


Caveats with callback refs

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.
*/

ReactDOM.render(<Sum/>, document.getElementById('root'))
